#!/usr/bin/env python
import sys
from os.path import isfile

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import numpy as N

from ui_ErrorBarSetup import Ui_Define_Plot_Widget
from Plot_Widget_Line2D import Plot_Widget
from plotDataClass import LPC


class Define_Error_Plot(QWidget):
    def __init__(self, global_list, local_Dict, varDict, append = False,  parent = None):
        QWidget.__init__(self, None)
        self.ui = Ui_Define_Plot_Widget()
        self.ui.setupUi(self)
        
        self.append = append
        self.parent = parent
        #print self.parent.dialog_test
        self.varDict = varDict
        self.localDict = local_Dict
        self.arrayLen = None
        self.x_len =  None
        self.x_equal = True
        self.y_len = None
        self.y_equal = True
        
        self.active_LPC = None
        self.x_array = None
        self.xLabel = None
        self.y_array = None
        self.yLabel = None
        
        self.initialize_setup(global_list,  local_Dict)

        self.connect(self.ui.btn_PlotSelection, SIGNAL("clicked()"), self.addErrorBars)
        self.connect(self.ui.active_listWidget, SIGNAL("currentRowChanged(int)"), self.getActivePlot)
        self.connect(self.ui.x_listWidget, SIGNAL("currentRowChanged(int)"), self.getXListSelections)
        self.connect(self.ui.y_listWidget, SIGNAL("currentRowChanged(int)"), self.getYListSelections)
        
        self.getActivePlot(0)
        
        
    def initialize_setup(self, global_list,  local_Dict):
        if global_list is not None:
            local_list = local_Dict.keys()
            self.ui.x_listWidget.addItem('None')
            self.ui.x_listWidget.addItems(global_list)
            self.ui.x_listWidget.setCurrentRow(0)
            self.ui.y_listWidget.addItem('None')
            self.ui.y_listWidget.addItems(global_list)
            self.ui.y_listWidget.setCurrentRow(0)
            self.ui.active_listWidget.addItems(local_list)
            self.ui.active_listWidget.setCurrentRow(0)
    
    def getActivePlot(self, index):
        active_item = str(self.ui.active_listWidget.item(index).text())
        if active_item != 'None':
            self.active_LPC = self.localDict.get(active_item)
            try:
                if type(self.active_LPC.data.get_xdata()) is N.ndarray:
                    self.arrayLen = self.active_LPC.data.get_xdata().size
            except:
                print "Error getting active lineplot class x array."
        
        self.getXListSelections(self.ui.x_listWidget.currentRow())
        self.getYListSelections(self.ui.y_listWidget.currentRow())
        #self.arrayLen = None
        
    def getXListSelections(self, index):
        x_item = str(self.ui.x_listWidget.item(index).text())#gets data in X ListWidget
        if x_item != 'None':
            self.x_array = self.varDict.get(x_item)
            #try:
            if type(self.x_array) is N.ndarray:
                self.x_len = self.x_array.size
                if self.arrayLen == self.x_len:
                    self.xLabel = x_item
                    self.x_equal = True
                else:
                    self.x_equal = False
            self.arraysEqual()
            #except:
                #print "Error getting x length"
        else:
            self.x_equal = True
         
    
    def getYListSelections(self, index):
        y_item = str(self.ui.y_listWidget.item(index).text())#gets data in Y ListWidget
        if y_item != 'None':
            
            self.y_array = self.varDict.get(y_item)
            #try:
            if type(self.y_array) is N.ndarray:
                self.y_len = self.y_array.size
                if self.arrayLen == self.y_len:
                    self.yLabel = y_item
                    self.y_equal = True
                else:
                    self.y_equal = False
            self.arraysEqual()
            #except:
                #print "Error getting y length"
        else:
            self.y_equal = True
    
    def arraysEqual(self):
        if self.x_equal and self.y_equal:
            self.ui.btn_PlotSelection.setEnabled(True)
            #print "button enabled"
        else:
            #print "btn disabled"
            self.ui.btn_PlotSelection.setDisabled(True)
    

    def addErrorBars(self):
        if self.active_LPC:
            if self.x_equal:
                self.active_LPC.set_xerr(self.x_array,  self.xLabel)
            else:
                self.active_LPC.clear_xerr()
                
            if self.y_equal:
                self.active_LPC.set_yerr(self.y_array,  self.yLabel)
            else:
                self.active_LPC.clear_yerr()
                
            self.parent.initialize_plot(self.active_LPC)
            self.close()
            
    
#    def __plotData__(self, data2plot):
#        if self.append is False:
#            self.plot_dialog = Plot_Widget(LPC(data2plot),self.parent)
#            self.plot_dialog.show()
#            self.close()
#        else:
#            self.parent.add_trace(data2plot)
#            self.close()
        
    
    
    def program_close(self):
        sys.exit()

    
if __name__ == "__main__":
    array_list = ["Banana", "Apple", "Elderberry", "Clementine", "Fig",
             "Guava", "Mango", "Honeydew Melon", "Date", "Watermelon",
             "Tangerine", "Ugli Fruit", "Juniperberry", "Kiwi",
             "Lemon", "Nectarine", "Plum", "Raspberry", "Strawberry",
             "Orange"]
            
    app = QApplication(sys.argv)
    plot_setup = Define_Plot_Widget(array_list)
    plot_setup.show()
    sys.exit(app.exec_())

